<script setup lang="ts">
import { addPatientMsg, delPatientMsg, editPatientMsg, patientInfoList } from '@/apis/user';
import type { PatientDataType, PatientInfoList } from '@/types/user';
import { rulesIdCard, rulesName } from '@/utils/rules';
import { showConfirmDialog, showSuccessToast, type FormInstance } from 'vant';
import { computed, onMounted, ref } from 'vue';

defineOptions({
  name: 'PatientPage'
})
const patientList = ref<PatientInfoList>([])
//获取患者列表信息
const patientListData = async () => {
  const res = await patientInfoList()
  console.log(res)
  patientList.value = res.data
  // 设置默认选中的ID，当你是选择患者的时候，且有患者信息的时候
  if (isChange.value && patientList.value.length) {
    //找到默认选中
    const defaultFlag = patientList.value.find(item => item.defaultFlag === 1)
    if (defaultFlag) {
      //默认选中高亮
      selectedId.value = defaultFlag.id
    } else {
      //没有默认选中就第一个高亮
      selectedId.value = patientList.value[0].id
    }
  }
}

onMounted(() => {
  patientListData()
})

//单选框分组
const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 0, }
]
//控制弹出层
const show = ref(false)
const showPopup = (item?: PatientDataType) => {
  //编辑功能
  if (item) {
    const { id, name, idCard, gender, defaultFlag } = item
    addPatientInfo.value = { id, name, idCard, gender, defaultFlag }
  } else {
    //重置表单
    addPatientInfo.value = {
      name: '',
      idCard: '',
      defaultFlag: 0,
      gender: 1
    }
  }
  show.value = true
}
//关闭弹出层
const closed = () => {
  show.value = false
}

//定义添加患者信息数据
const addPatientInfo = ref<PatientDataType>({
  name: '',
  idCard: '',
  defaultFlag: 0,
  gender: 1
})
//复选框修改响应
const defaultFlag = computed({
  get() {
    return addPatientInfo.value.defaultFlag === 1
  },
  set(val) {
    addPatientInfo.value.defaultFlag = val ? 1 : 0
  }
})

//保存按钮数据
const form = ref<FormInstance>()
const onSubmit = async () => {
  //对表单预校验
  await form.value?.validate()
  const gender = Number(addPatientInfo.value.idCard?.slice(-2, -1)) % 2
  //验证身份性别
  if (addPatientInfo.value.gender !== gender) {
    await showConfirmDialog({
      title: '提示消息',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗？',
    })
  }
  //发送请求
  addPatientInfo.value.id ? await editPatientMsg(addPatientInfo.value) : await addPatientMsg(addPatientInfo.value)
  //提示用户
  showSuccessToast(addPatientInfo.value.id ? '编辑患者成功' : '添加患者成功')
  //关闭弹层
  show.value = false
  //获取列表数据
  patientListData()
}

//删除
const onDelete = async () => {
  if (addPatientInfo.value.id) {
    await showConfirmDialog({
      title: '确认消息',
      message: '确认删除吗？',
    })
    await delPatientMsg(addPatientInfo.value.id)
    showSuccessToast('删除患者成功')
    show.value = false
    //获取列表数据
    patientListData()
  }
}

//是否是选择患者
import { useRoute } from 'vue-router'
const route = useRoute()
const isChange = computed(() => route.query.isChange === '1')

//点击患者高亮
//获取高亮id
const selectedId = ref<string>()
const selectedPatient = (item: PatientDataType) => {
  //只有选择患者才能点击高亮
  if (isChange.value) selectedId.value = item.id
}
//点击下一步
import { useConsultStore } from '@/stores'
import router from '@/router';
const store = useConsultStore()
const next = () => {
  // 记录患者ID跳转到待支付页面
  if (!selectedId.value) return
  store.setPatient(selectedId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>

    <div class="patient-list">
      <div class="patient-item" v-for="item in patientList" :key="item.id" @click="selectedPatient(item)"
        :class="{ selected: selectedId === item.id }">
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <span class="id">{{ item.idCard?.replace(/^(\w{6})(\w{8})(\w{4})$/, '$1********$3') }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon"><cp-icon name="user-edit" @click="showPopup(item)" /></div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>

      <div class="patient-add" v-if="patientList.length < 6" @click="showPopup()">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
      <!-- 底部按钮 -->
      <div class="patient-next" v-if="isChange">
        <van-button type="primary" @click="next" round block>下一步</van-button>
      </div>

    </div>
    <!-- 侧边栏 -->
    <van-popup v-model:show="show" position="right">
      <cp-nav-bar :title="addPatientInfo.id ? '编辑患者' : '添加患者'" right-text="保存" :back="closed"
        @click="onSubmit"></cp-nav-bar>
      <van-form autocomplete="off" ref="form">
        <van-field label="真实姓名" placeholder="请输入真实姓名" v-model="addPatientInfo.name" :rules="rulesName" />
        <van-field label="身份证号" placeholder="请输入身份证号" v-model="addPatientInfo.idCard" :rules="rulesIdCard" />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <!-- 双向数据绑定完整写法 -->
            <!-- <cp-radio-btn :genderOptions="genderOptions" :modelValue="gender"
        @update:modelValue="gender = $event"></cp-radio-btn> -->
            <cp-radio-btn :genderOptions="genderOptions" v-model="addPatientInfo.gender"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox :icon-size="18" round v-model="defaultFlag" />
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="addPatientInfo.id">
        <van-action-bar-button type="danger" text="删除" @click="onDelete" />
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;

  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}

.patient-change {
  padding: 15px;

  >h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }

  >p {
    color: var(--cp-text3);
  }
}

.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

.patient-list {
  padding: 15px;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;

  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;

    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;

      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }

      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }

  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }

  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);

    .icon {
      color: var(--cp-primary);
    }
  }
}

.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;

  .cp-icon {
    font-size: 24px;
  }
}

.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}

.pb4 {
  padding-bottom: 4px;
}
</style>